package com.zhongshengnetwork.rightbe.lang.view;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.FragmentViewPageAdapter;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.clerk.view.ClerkFragment;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.topgrid.activity.TopGridActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.wzt.view.WZTLatestFragment;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseAnalyticsFragment {

    private View rootView;
    private ViewPager mPaper;
    private ImageView home_menu;
    private ViewPagerIndicator viewPagerIndicator;
    private LinearLayout home_layout;
    private View home_layout_line;
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private int select = 0;
    //FragmentViewPageAdapter fragmentViewPageAdapter;
    //private FragmentStatePagerAdapter adapter;
    public MainActivity mainActivity;

    private List<String>titleList = new ArrayList<String>();
    private List<String>typeList = new ArrayList<String>();
    //已经选择的id
    ArrayList<String> selectIds = new ArrayList<String>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //System.out.print("首页界面创建\n");
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null){
            rootView = inflater.inflate(R.layout.home_layout, container,false);
            viewPagerIndicator = (ViewPagerIndicator) rootView.findViewById(R.id.indicator);
            mPaper = (ViewPager)rootView.findViewById(R.id.viewpager);
            home_menu = (ImageView) rootView.findViewById(R.id.home_menu);
            //设置主题下的图标
            home_menu.setImageResource(AppThemeUtils.getInstance().getHomeMenuIcon());

            home_menu.setClickable(true);
            home_menu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (getActivity() != null){

                        if(CommonUtils.isLogin() == false){
                            Intent intent = new Intent(getActivity(), LoginActivity.class);
                            getActivity().startActivity(intent);
                            return;
                        }
                        int currentSelectType = 0;
                        if (mPaper != null && typeList != null && typeList.size() > 0 && typeList.size() > mPaper.getCurrentItem()){
                            currentSelectType = Integer.valueOf(typeList.get(mPaper.getCurrentItem()));
                        }
                        Intent intent = new Intent(getActivity(), TopGridActivity.class);
                        intent.putExtra("currentSelectType", currentSelectType);
                        getActivity().startActivityForResult(intent, MainActivity.REQUEST_HOME_MENU);

                    }
                }
            });
            //设置主题下的颜色
            home_layout = (LinearLayout) rootView.findViewById(R.id.home_layout);
            home_layout_line = (View) rootView.findViewById(R.id.home_layout_line);
            home_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            home_layout_line.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            RelativeLayout home_menu_bg = (RelativeLayout) rootView.findViewById(R.id.home_menu_bg);
            home_menu_bg.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

            addData(false, -1, false);

            updateCareTip(false);
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        return rootView;
    }

    public void addData(boolean isUpdateUI, int selectType, boolean isSelect){

        if (isSelect == true && mPaper != null && mPaper.getAdapter() != null){//单纯选择
            if (typeList.contains(""+selectType)){
                mPaper.setCurrentItem(typeList.indexOf(""+selectType), true);
            }
            return;

        }

        if (isUpdateUI == true && mPaper != null && mPaper.getAdapter() != null){//清除老数据
            if (mFragments.size() > 0 && getActivity() != null){
                try {
                    FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                    if (ft != null){
                        for (Fragment f : mFragments){
                            ft.remove(f);
                        }
                        ft.commit();
                        ft = null;
                        getActivity().getSupportFragmentManager().executePendingTransactions();
                        mFragments.clear();
                        typeList.clear();
                        titleList.clear();
                        selectIds.clear();
                        mPaper.getAdapter().notifyDataSetChanged();
                    }
                }catch (Exception e){
                    LangPublishActivity.uploadError("移除频道报错："+e.getLocalizedMessage());
                }
            }
        }

        //取固定的
        List<String> solidNames = CommonUtils.stringToArrayList(AdvertUtils.DefaultSolidChannelNameData);
        List<String> solidIds = CommonUtils.stringToArrayList(AdvertUtils.DefaultSolidChannelData);
        if (solidIds != null && solidIds.size() > 0){
            typeList.addAll(solidIds);
            titleList.addAll(solidNames);
            selectIds.addAll(solidIds);
        }

        //取平台推荐的
        String newData = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.NewChannelDataKey, "");
        String newDataName = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.NewChannelNameDataKey, "");
        if(!CommonUtils.isEmpty(newData)){
            List<String> newDatas = CommonUtils.stringToArrayList(newData);
            List<String> newDataNames = CommonUtils.stringToArrayList(newDataName);
            if (newDatas != null && newDatas.size() > 0){
                for (int i = 0; i < newDatas.size(); i++){
                    if (selectIds.contains(newDatas.get(i)) == false){
                        typeList.add(newDatas.get(i));
                        titleList.add(newDataNames.get(i));
                        if (select == 0){
                            select = titleList.size()-1;
                        }
                        selectIds.add(newDatas.get(i));
                    }

                }
            }
        }

        //登录取作者
        boolean isGetUser = false;
        if (CommonUtils.isLogin() == true){
            isGetUser = true;
            String myData = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.MyChannelDataKey+CustomApplication.loginModel.getUid(), "");
            if (!CommonUtils.isEmpty(myData)){
                String myDataName = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.MyChannelNameDataKey+CustomApplication.loginModel.getUid(), "");
                List<String> myDatas = CommonUtils.stringToArrayList(myData);
                List<String> myDataNames = CommonUtils.stringToArrayList(myDataName);
                if (myDatas != null && myDatas.size() > 0){
                    for (int i = 0; i < myDatas.size(); i++){
                        if (selectIds.contains(myDatas.get(i)) == false){
                            typeList.add(myDatas.get(i));
                            titleList.add(myDataNames.get(i));
                            if (select == 0){
                                select = titleList.size()-1;
                            }
                            selectIds.add(myDatas.get(i));
                        }
                    }
                }
            }
        }

        if (isGetUser == false){
            solidNames = CommonUtils.stringToArrayList(AdvertUtils.DefaultChannelNameData);
            solidIds = CommonUtils.stringToArrayList(AdvertUtils.DefaultChannelData);
            if (solidIds != null && solidIds.size() > 0){
                for (int i = 0; i < solidIds.size(); i++){
                    if (selectIds.contains(solidIds.get(i)) == false){
                        typeList.add(solidIds.get(i));
                        selectIds.add(solidIds.get(i));
                        titleList.add(solidNames.get(i));
                        if (select == 0){
                            select = titleList.size()-1;
                        }
                    }
                }
            }
        }

        if (typeList != null && typeList.size() > 0){
            for (int i = 0; i < typeList.size(); i++){
                //"推荐,最新,关注,文案,微纸条"
                if (typeList.get(i).equals("-1")){
                    mFragments.add(new HotLangFragment());
                }else if (typeList.get(i).equals("-2")){
                    mFragments.add(new LatestLangFragment());
                }else if (typeList.get(i).equals("-3")){
                    mFragments.add(new CareLangFragment());
                }else if (typeList.get(i).equals("-4")){
                    mFragments.add(new ClerkFragment());
                }else if (typeList.get(i).equals("-5")){
                    WZTLatestFragment wztFragment = new WZTLatestFragment();
                    mFragments.add(wztFragment);
                }else if(typeList.get(i).equals("21")){
                    //话题探索
                    TopicFragment topicFragment = new TopicFragment();
                    topicFragment.type = 1;
                    mFragments.add(topicFragment);
                }else if (typeList.get(i).equals("30") || typeList.get(i).equals("44")){
                    ShareLangFragment shareLangFragment = new ShareLangFragment();
                    shareLangFragment.isLangType = true;
                    shareLangFragment.getType = Integer.valueOf(typeList.get(i));
                    shareLangFragment.typeName = titleList.get(i);
                    mFragments.add(shareLangFragment);
                }else if(typeList.get(i).equals("54") || typeList.get(i).equals("26")){//以句会友和想法句子
                    WeijuBannerFragment weijuBannerFragment = new WeijuBannerFragment();
                    weijuBannerFragment.isLangType =true;
                    weijuBannerFragment.getType = Integer.valueOf(typeList.get(i));
                    weijuBannerFragment.typeName = titleList.get(i);
                    mFragments.add(weijuBannerFragment);
                } else {
                    WeijuFragment weijuFragment = new WeijuFragment();
                    weijuFragment.isLangType =true;
                    weijuFragment.getType = Integer.valueOf(typeList.get(i));
                    weijuFragment.typeName = titleList.get(i);
                    mFragments.add(weijuFragment);
                }
            }
        }
        Log.e("TAG","mFragments大小："+mFragments.size());
        FragmentStatePagerAdapter adapter = new FragmentStatePagerAdapter(getActivity().getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titleList.get(position);
            }

            /**
             * 使用这个方式，让页面不缓存，能够在清除fragment的时候对其做了删除
             *
             * @param object
             * @return
             */
            @Override
            public int getItemPosition(Object object) {
                return PagerAdapter.POSITION_NONE;
            }

        };
        mPaper.setAdapter(adapter);
        viewPagerIndicator.setViewPager(mPaper);

        /*
        if (typeList.contains(""+selectType)){
            mPaper.setCurrentItem(typeList.indexOf(""+selectType));
        }else{
            mPaper.setCurrentItem(1);
        }
        */
        mPaper.setCurrentItem(1);

        mPaper.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                Log.e("TAG", "当前选择的是："+position);

                if (position == 0){
                    if (typeList != null && typeList.size() > 0){
                        if (typeList.contains("-3")){
                            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.CareUpdateKey,"0");
                            updateCareTip(false);
                        }
                    }
                }

                /*
                if (typeList != null && typeList.size() > 0){
                    if (typeList.contains("-3")){
                        int index = typeList.indexOf("-3");
                        Object object = mFragments.get(index);
                        if (object != null && object instanceof CareLangFragment){
                            CareLangFragment careLangFragment = (CareLangFragment)object;
                            careLangFragment.getLatest();
                        }
                    }
                }
                */

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void updateAfterLogin(){
         if (typeList != null && typeList.size() > 0){
             if (typeList.contains("-3")){
                 int index = typeList.indexOf("-3");
                 Object object = mFragments.get(index);
                 if (object != null && object instanceof CareLangFragment){
                     CareLangFragment careLangFragment = (CareLangFragment)object;
                     careLangFragment.getFirstData(true);
                 }
             }
         }
    }

    public void getNewData(){

        if (mPaper != null && mFragments != null && mFragments.size() > mPaper.getCurrentItem() && mPaper.getCurrentItem() >= 0){
            Object object = mFragments.get(mPaper.getCurrentItem());
            if (object != null){
                if (object instanceof HotLangFragment){
                    HotLangFragment hotLangFragment = (HotLangFragment)object;
                    hotLangFragment.getNewData();
                }else if (object instanceof CareLangFragment){
                    CareLangFragment careLangFragment = (CareLangFragment)object;
                    if (CommonUtils.isLogin() == true){
                        careLangFragment.updateFirstPage();
                    }
                }else if (object instanceof LatestLangFragment){
                    LatestLangFragment latestLangFragment = (LatestLangFragment)object;
                    latestLangFragment.updateFirstPage();
                }else if (object instanceof WZTLatestFragment){
                    WZTLatestFragment wztLatestFragment = (WZTLatestFragment)object;
                    wztLatestFragment.updateFirstPage();
                }else if(object instanceof TopicFragment){
                    TopicFragment topicFragment = (TopicFragment)object;
                    topicFragment.updateFirstPage();
                }else if (object instanceof ShareLangFragment){
                    ShareLangFragment shareLangFragment = (ShareLangFragment)object;
                    shareLangFragment.updateFirstPage();
                }else if (object instanceof WeijuBannerFragment){
                    WeijuBannerFragment weijuBannerFragment = (WeijuBannerFragment)object;
                    weijuBannerFragment.updateFirstPage();
                }else if (object instanceof WeijuFragment){
                    WeijuFragment weijuFragment = (WeijuFragment)object;
                    weijuFragment.updateFirstPage();
                }
            }
        }

        /*
        if (typeList != null && typeList.size() > 0){
            if (typeList.contains("-1")){
                int index = typeList.indexOf("-1");
                if (mPaper.getCurrentItem() == index){
                    Object object = mFragments.get(index);
                    if (object != null){
                        if (object instanceof HotLangFragment){
                            HotLangFragment hotLangFragment = (HotLangFragment)object;
                            hotLangFragment.getNewData();
                        }else if (object instanceof CareLangFragment){
                            CareLangFragment careLangFragment = (CareLangFragment)object;
                            if (CommonUtils.isLogin() == true){
                                careLangFragment.updateFirstPage();
                            }
                        }else if (object instanceof LatestLangFragment){
                            LatestLangFragment latestLangFragment = (LatestLangFragment)object;
                            latestLangFragment.updateFirstPage();
                        }
                    }

                }

            }
        }
        */

    }

    public void setFragmentOfIndex(int select){
        mPaper.setCurrentItem(select);
    }

    public void scrollToFirstData(){

        if (mPaper == null || typeList == null || typeList.size() <= mPaper.getCurrentItem()){
            return;
        }

        int select = mPaper.getCurrentItem();
        //int type = Integer.valueOf(typeList.get(select));
        //"推荐,最新,关注,文案,微纸条"

        Object object = mFragments.get(select);

        if (object instanceof HotLangFragment){
            HotLangFragment hotLangFragment = (HotLangFragment)object;
            hotLangFragment.getFirstData(true);
        }else if (object instanceof LatestLangFragment){
            LatestLangFragment latestLangFragment = (LatestLangFragment)object;
            latestLangFragment.getFirstData(true);
        }else if (object instanceof CareLangFragment){
            CareLangFragment careLangFragment = (CareLangFragment)object;
            careLangFragment.getFirstData(true);
        }else if (object instanceof ClerkFragment){
            ClerkFragment clerkFragment = (ClerkFragment)object;
            clerkFragment.getFirstData(true);
        }else if (object instanceof WZTLatestFragment){
            WZTLatestFragment wztFragment = (WZTLatestFragment)object;
            wztFragment.getFirstData(true);
        }else if (object instanceof ShareLangFragment){
            ShareLangFragment shareLangFragment = (ShareLangFragment)object;
            shareLangFragment.getFirstData(true);
        }else if (object instanceof WeijuFragment){
            WeijuFragment weijuFragment = (WeijuFragment)object;
            weijuFragment.getFirstData(true);
        }else if (object instanceof WeijuBannerFragment){
            WeijuBannerFragment weijuFragment = (WeijuBannerFragment)object;
            weijuFragment.getFirstData(true);
        }else if (object instanceof TopicFragment){
            TopicFragment topicFragment = (TopicFragment)object;
            topicFragment.getFirstData(true);
        }


    }

    public void updateWZT(){
        if (typeList != null && typeList.size() > 0){
            if (typeList.contains("-5")){
                int index = typeList.indexOf("-5");
                Object object = mFragments.get(index);
                if (object != null && object instanceof WZTLatestFragment){
                    WZTLatestFragment wztFragment = (WZTLatestFragment)object;
                    wztFragment.updateData();
                }
            }
        }
    }

    public void updateCareTip(Boolean visible){

        if (viewPagerIndicator != null){
            String tip = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.CareUpdateKey,"0");
            if (tip.equals("1") && CommonUtils.isLogin() == true){
                viewPagerIndicator.setCare(true);
            }else {
                viewPagerIndicator.setCare(false);
            }
        }
    }


}
